<?php
if(!defined('BASE_DIR'))die('Cannot access the file !');
/**
 * -+-----------------------------------------
 * |PHP Framework
 * |Copyright (c) 2010 jinke.[iblue.cc]
 * |E-mail: mejinke@gmail.com
 * |Date: 2010-03-08
 * |Update: 2010-11-4
 * -+-----------------------------------------
 *
 * Mysql 数据库驱动
 * @author jinke
 */
class MysqlDB extends Base
{

	//结果集
	private $result;
	//数据库名称
	public $dbName='';
	//连接标识
	private $_link;


	//数据库资料数组
	public $dbConfig = '';

	//事务标识
	private $transTimes = 0;
	
	public $show_sql = false;
	
	/**
	 * 构造函数，初始化配置文件
	 * @access public
	 * @param array $db_connect 数据配置资料
	 */
	public function __construct(Array $db_connect,$dbName)
	{

		if (empty($db_connect))
		{
			
			message_error('MySQL Error','数据库资料加载错误！',message_debug(debug_backtrace()));
		}
		else{
			$db_connect['dbname']=$dbName;
			$this->dbConfig = $db_connect;
			//数据库名称
			$this->dbName = $this->dbConfig['dbname'];
		}
		
		Debug::initClass('MysqlDB.class.php host=>'.$this->dbConfig['hostname'].' database=>'.$dbName);
	}


	/**
	 * 连接Mysql数据库
	 * @access private
	 * @return void
	 */
	private function _connect()
	{
		if (is_null($this->_link))
		{ 

			$database = Config::get('database');
			$this->_link = mysql_connect(
			$this->dbConfig['hostname'],
			$this->dbConfig['username'],
			$this->dbConfig['password']
			) or message_error('Mysql Error','无法连接Mysql服务器！',message_debug(debug_backtrace()));
			 mysql_query("set names '".$database['db_char']."'",$this->_link);
			

		}
	}


	/**
	 * 执行SQL语句,并自动将结果集组合为数组
	 * @access public
	 * @param string $sql SQL语句
	 * @return mixed 查询结果
	 */
	public function query($sql)
	{
	 	return $this->_query($sql);
	 }


	/**
	 * 执行SQL语句
	 * @access public
	 * @param string $sql SQL语句
	 * @return void
	 */
	public function exec($sql)
	{
		
		Debug::$sqlCount++;
	 	$this->_connect();
	 	$time1=Functions::getMicroTime();
	 	$result =  mysql_query($sql,$this->_link);
		//$this->_link = null;
	 	$time2=Functions::getMicroTime()-$time1;
		Debug::$sqlTime+=$time2;
		$string=$sql.' '.sprintf('%.6f',$time2).' seconds';
		if($time2>0.1)
			$string='<span style="color:red">'.$string.'</span>';
	 	Debug::$sqls[Functions::REG('_MODEL_NAME_')][]=$string;
	 	return $result;
	 }


	/**
	 * 执行SQL语句,并自动将结果集组合为数组
	 * @access private
	 * @param string $sql SQL语句
	 * @return mixed 查询结果
	 */
	private function _query($sql)
	{
	 
		$tep_array = false;
		try{
			if ($rs = $this->exec($sql))
			{
				while($row = mysql_fetch_assoc($rs))
				{
					$tep_array[] = $row;
				}
			}
		}
		catch (Exception $e)
		{
			return false;
		}
		Functions::RES(md5($sql),$tep_array);
		return $tep_array;
	}




	/**
	 * 获取一张表的数据
	 * @access public
	 * @param string  $table  表名称
	 */
	public function get($table)
	{

		$sql='SELECT * FROM`'.$table.'`';
		$result = $this->_query($sql);
		return $result;
	}


	/**
	 * 获取上一次插入数据时生成的ID
	 * @access public
	 * @return int
	 */
	public function getId()
	{
		return ($id = mysql_insert_id($this->_link)) >= 0 ?
		$id :
		@mysql_result($this->exec("SELECT last_insert_id()"), 0);
	}

	/**
	 * 获取指定表的所有字段
	 * @access public
	 * @param string $table 表名称
	 * @return array
	 */
	public function getFields($table)
	{
		//连接数据库
		$this->_connect();
		$tepArray = false;

		//获取表字段信息
		if($this->tableIsExist($table))
		{
			$fields = mysql_list_fields($this->dbName, $table, $this->_link);
			$columns = mysql_num_fields($fields);
			for ($i = 0; $i < $columns; $i++)
			{
				$tepArray[$i]=mysql_field_name($fields, $i);
			}
			return $tepArray;
		}


	}

	/**
	 * 检测给定的表名称是否存在当前库中
	 * @access public
	 * @param string $table 表名称
	 * @return array
	 */
	public function tableIsExist($table)
	{
		$sql="SHOW TABLES FROM  `".$this->dbName."` like '".$table."'";
		return $this->query($sql);
	}


	/**
	 * 添加一条记录
	 * @access public
	 * @param array $data 资料数组
	 * @param string $table 表名称
	 * @return mixed 成功返回ID 失败返回 false
	 */
	public function insert($data,$table)
	{
		foreach($data as $key=>$val)
		{
			//过滤非标量
			if(is_scalar($val))
			{
				$values[] = "'".DBTool::escape($val)."'";
				$fields[] = '`'.$key.'`';
			}
		}
		
		 $sql   =  'INSERT INTO  `'.$this->dbName.'`.`'.$table.'` ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
		if ($this->show_sql)
			die($sql);
		 if ($this->exec($sql))
		 	return $this->getId();
		 else
			return false;
	}


	/**
	 * 更新记录
	 * @access public
	 * @param array	$data	数据数组
	 * @param string $table	表名称
	 * @param string $where	条件
	 * @return mixed
	 */
	public function update($data,$table,$where)
	{
		$set = array();
		foreach($data as $key=>$val)
		{
			//过滤非标量
			if(is_scalar($val))
				$set[] = '`'.$key."`='".DBTool::escape($val)."'";
		}
		if(empty($set))
			return false;

		$sql   =  'UPDATE  `'.$this->dbName.'`.`'.$table.'`   SET '.implode(',',$set).'  '.$where;
		if ($this->show_sql)
			die($sql);
		return $this->exec($sql);
	}

	/**
	 * 删除记录
	 * @access public
	 * @param string $table	表名称
	 * @param string $where	 条件串
	 * @return mixed
	 */
	public function delete($table,$where)
	{
		$sql = 'DELETE FROM `'.$this->dbName.'`.`'.$table.'` '.$where;
		 return $this->exec($sql);
	}

	 /**
      * 启动事务
      * @access public
      * @return void
      */
    public function startTrans()
	{
        if ($this->transTimes == 0)
		{
            $this->exec('START TRANSACTION');
        }
        $this->transTimes++;
        return ;
    }


    /**
     * 在开启事务时，提交查询
     * @access public
     * @return bool
     */
    public function commit()
	{
        if ($this->transTimes > 0)
		{
            $this->result = $this->exec('COMMIT');
            $this->transTimes = 0;
            if(!$this->result)
                return false;
			else
				return true;
        }
        return true;
    }

    /**
     * 事务回滚
     * @access public
     * @return true
     */
    public function rollback()
	{
        if ($this->transTimes > 0)
		{
            $this->result = $this->exec('ROLLBACK');
            $this->transTimes = 0;
            if(!$this->result)
                throw_exception($this->error());
        }
        return true;
    }


	/**
     * 数据库执行错误时提示
     * @access public
     */
    public function error()
	{
        $this->error = mysql_error($this->_link);
        $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
        return $this->error;
    }



	/**
	 * 析构函数 关闭数据库
	 * @access public
	 * @return void
	 */
	public function __destruct()
	{
		return;
		if (!is_null($this->_link))
		{
			if (@mysql_error($this->_link))
				message_error('Mysql Error',mysql_error($this->_link));
			mysql_close($this->_link);
		}
	}

}
?>
